import Vue from 'vue'
import VueRouter from 'vue-router'
import { getNav } from '../utils/http.js'
import store from '../store'
Vue.use(VueRouter)
let routes = [
  {
    path: '/',
    component: () => import('../pages/HomePage.vue'),
    name: 'myHome',
    children: [],
  },
]

const router = new VueRouter({
  mode: 'history',
  routes,
})

//路由拦截
router.beforeEach(async (to, from, next) => {
  /**
   * 添加该判断是为了提高性能
   * 如果是第一次进来，没有缓存， 那么调用接口，请求数据
   * 如果缓存中存在， 则直接进行路由跳转
   */
  if (store && store.state.nav.length === 0) {
    //获取路由数据
    const res = await getNav()
    //缓存数据 vuex
    store.dispatch('SETNAV', res.data.data)
    //动态添加路由数据
    //转换后端返回得数据处理成路由数据
    let dynamicRoutes = addDynamicRoutes(res.data.data)
    router.addRoutes(dynamicRoutes) //动态添加路由
    // next()
    // next({path:to.path})
    //简写方法
    next({ ...to })
  } else {
    next()
  }
})
const addDynamicRoutes = (res) => {
  res.forEach((item) => {
    const { url, name, title } = item
    routes[0].children.push({
      path: url,
      name: name,
      meta: { title },
      title: title,
      component: () => import(`../pages/${name}`),
    })
  })
  return routes
}
export default router
